package com.henry.db.migrate.main;

import com.henry.db.migrate.factory.DbFactory;
import com.henry.db.migrate.util.RandomValueUtil;
import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Random;
import java.util.UUID;

public class InitialSourceDataThread extends Thread {
    private static final Logger logger = Logger.getLogger(InitialSourceDataThread.class);
    private int num;

    public InitialSourceDataThread(int num) {
        this.num = num;
    }

    @Override
    public void run() {
        logger.info("线程[" + num + "]正在运行...");
        Connection srcConn = DbFactory.getConnection("src");
        try {
            srcConn.setReadOnly(false);
            srcConn.setAutoCommit(false);
            String sql = "insert into user(uuid, name, sex, address, phone,col1,col2,col3,col4,col5) values (?,?,?,?,?,?,?,?,?,?)";
            PreparedStatement preparedStatement = srcConn.prepareStatement(sql);
            Random random = new Random();
            for (int i = 0; i < 10000; i++) {
                preparedStatement.setObject(1, UUID.randomUUID().toString());
                preparedStatement.setObject(2, RandomValueUtil.getChineseName());
                preparedStatement.setObject(3, random.nextInt(2));
                preparedStatement.setObject(4, RandomValueUtil.getAddress().toString());
                preparedStatement.setObject(5, RandomValueUtil.getTel());
                preparedStatement.setObject(6, RandomValueUtil.getEmail(15, 50));
                preparedStatement.setObject(7, RandomValueUtil.getAddress().toString());
                preparedStatement.setObject(8, RandomValueUtil.getAddress().toString());
                preparedStatement.setObject(9, RandomValueUtil.getAddress().toString());
                preparedStatement.setObject(10, RandomValueUtil.getAddress().toString());

                preparedStatement.addBatch();
                if (i % 1000 == 999) {
                    preparedStatement.executeBatch();
                    srcConn.commit();
                    preparedStatement.clearBatch();
                    logger.info("线程[" + num + "]插入1000条数据成功");
                }
            }
            preparedStatement.executeBatch();
            srcConn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            DbFactory.rollback(srcConn);
        }finally {
            DbFactory.close(srcConn);
        }
        logger.info("线程[" + num + "]运行结束...");
    }
}
